import {findStore, getCitys} from '@/service'
import {Message} from "element-ui";


export default {
  namespaced: true,
  state() {
    return {
      rest: [],
      citys: [],
      loading: false
    }
  },
  getter: {},
  mutations: {
    /**
     * 状态设置器
     * @param state
     * @param {Object} payload  key:建，value:值，isStorage=true同时设置缓存，isStorage=false不设置缓存
     * @constructor
     */
    SET_STATE(state, payload) {
      state[payload.key] = payload.value
      if (payload.isStorage) {
        localStorage.setItem(payload.key, payload.value)
      }
    }
  },


  actions: {
    /**
     * 获取餐厅
     * @author 张晓东
     * @param commit
     * @param payload
     * @returns {Promise<never>}
     * @constructor
     */
    async LOAD_LIST({commit}, payload) {
      commit('SET_STATE', {key: 'loading', value: true})
      let source = await findStore(payload)// 获取店铺列表
      if (source.code === 200) {
        commit('SET_STATE', {key: 'rest', value: source.data})
        commit('SET_STATE', {key: 'loading', value: false})
      } else {
        if (source.code !== 401) {
          commit('SET_STATE', {key: 'loading', value: false})
          return Promise.reject(source.msg)
        }
      }
    },
    /**
     * 获取城市列表
     * @author 张晓东
     * @param commit
     * @returns {Promise<never>}
     * @constructor
     */
    async LODE_CITYS({commit}) {
      let source = await getCitys()
      if (source.code === 200) {
        let {data} = source
        commit("SET_STATE", {key:'citys',value:recursCity(data)})
      } else {
        if (source.code !== 401) {
          return Promise.reject(source.msg)
        }
      }
    }
  }
}

/**
 * 递归城市渲染新数据
 * @param data
 * @returns {Array}
 */
function recursCity(data) {
  let citys = []
  data.map(item => {
    let obj = {
      value: item.id,
      label: item.cityName || item.districtName
    }
    if (typeof item.districts === 'object') {
      obj.children = recursCity(item.districts)
    }
    citys.push(obj)
  })
  return citys
}
